package com.sjgs.gis.fs.store;

import com.sjgs.gis.common.RocksDBOptionsFactory;
import com.sjgs.gis.config.KVStoreProperties;
import com.sjgs.gis.fs.KVStore;
import com.sjgs.gis.errors.RocksIOException;
import org.rocksdb.DBOptions;
import org.rocksdb.RocksDB;
import org.rocksdb.WriteOptions;

public abstract class RocksStore implements KVStore {

    private RocksDB db;
    private DBOptions options;
    private WriteOptions writeOptions;

    private KVStoreProperties kvStoreProperties;

    public RocksStore(KVStoreProperties kvStoreProperties) {
        this.kvStoreProperties = kvStoreProperties;
        createDBOptions();
        createWriteOptions();
        if (!initStore()) {
            throw new RocksIOException("fail init rocksdb");
        }
    }

    @Override
    public Boolean initStore() {
        return false;
    }

    private void createDBOptions() {
        this.options = RocksDBOptionsFactory.getDefaultRocksDBOptions(kvStoreProperties);
    }

    private void createWriteOptions() {
        this.writeOptions = new WriteOptions();
        this.writeOptions.setSync(kvStoreProperties.isSync());
        // If `sync` is true, `disableWAL` must be set false.
        this.writeOptions.setDisableWAL(!kvStoreProperties.isSync() && kvStoreProperties.isDisableWal());
    }

    public KVStoreProperties getKvStoreProperties() {
        return kvStoreProperties;
    }

    public RocksDB getDb() {
        return db;
    }

    public DBOptions getOptions() {
        return options;
    }

    public WriteOptions getWriteOptions() {
        return writeOptions;
    }

}
